package cn.rwklyd.BookKeeping.service;
import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.exception.BaseException;
import cn.rwklyd.BookKeeping.util.JwtUtils;
import cn.rwklyd.BookKeeping.pojo.User;
import cn.rwklyd.BookKeeping.pojo.vo.LoginUser;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;


@Slf4j
@Service
public class SystemService {
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private TokenService tokenService;

    // 登录
    public Map<String, Object> Login(User user){

        // 第二步：封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(
                        user.getUsername(),
                        user.getPassword(),
                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));    // 封装用户名、密码、角色
        log.info("的第一步：{}", authenticationToken);

//       Authentication authentication = authenticationManager.authenticate(authenticationToken);     // 进行认证
//        if(Objects.isNull(authentication)){
//            throw new BaseException(MessageConstant.LOGIN_FAILED);
//        }

        // 第三步：AuthenticationManager 会调用 CustomUserDetailsService 的 loadUserByUsername 方法来加载用户信息
        // 第五步：调用完用户信息后，会自动调用封装好的 PasswordEncoder进行密码验证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        log.info("的第三步：{}", authentication);
        // 放入用户信息
        LoginUser e = (LoginUser) authentication.getPrincipal();  // 获取用户信息
        log.info("的放入用户信息：{}", e);
        //第六步：登录成功。生成并下发令牌
        
        // 将权限列表转换为JSON字符串
        String permissionsJson = JSON.toJSONString(e.getPermissions());
        
        // 使用TokenService创建访问令牌和刷新令牌
        Map<String, String> tokens = tokenService.createTokens(e.getUser().getId(), e.getUsername(), permissionsJson);

        Map<String, Object> responseData = new HashMap<>();
        responseData.put("user", e.getUser()); // 将用户对象放入响应数据中
        responseData.put("accessToken", tokens.get("accessToken")); // 将访问令牌放入响应数据中

        return responseData;  // 返回响应数据
    }

    /*
        云盾人机验证
     */
    private static final String SECRET_KEY = "0x4AAAAAAA9kcI_RTt4qgCFpa1m5BjTYLxM";
    private static final String TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";

    public boolean verifyTurnstile(String token) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> body = new HashMap<>();
        body.put("secret", SECRET_KEY);
        body.put("response", token);

        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(TURNSTILE_VERIFY_URL, body, Map.class);
        Map<String, Object> responseBody = responseEntity.getBody();

        return responseBody != null && (Boolean) responseBody.get("success");
    }
}
